#pragma once
#ifndef SIMPLELINKEDLISTORDERED_H
#define SIMPLELINKEDLISTORDERED_H

template <class T> class CSimpleLinkedList
{
private :
	typedef struct SNode{
		T elementNode;
		SNode* next;
	} node;

	node* beginList;

public:
	CSimpleLinkedList::CSimpleLinkedList(void);
	CSimpleLinkedList::~CSimpleLinkedList(void);
	void CSimpleLinkedList::addToList(T elementNode);
	void CSimpleLinkedList::deleteToList(void);
	void CSimpleLinkedList::clearList(void);
	void CSimpleLinkedList::displayList(void);
	T CSimpleLinkedList::getElement(int indexElement);

};

template <class T> CSimpleLinkedList<T>::CSimpleLinkedList(void)
{
	this->beginList=NULL;
}

template <class T> CSimpleLinkedList<T>::~CSimpleLinkedList(void)
{
	this->clearList();
	this->beginList=NULL;
}

/*function that add a element at the end of the list*/
template <class T> void CSimpleLinkedList<T>::addToList(T elementNode)
{
	node* current;
	node* next;
	current=this->beginList;
	//if the list is empty
	if(current==NULL)
	{
		this->beginList=new node;
		this->beginList->next=current;
		this->beginList->elementNode=elementNode;
	}
	else
	{
		//if there is only one element
		if(current->next==NULL)
		{
			current->next= new node;
			current->next->elementNode=elementNode;
			current->next->next=NULL;
		}
		else
		{
			//look for the last element
			while(current->next!=NULL)
			{
					current=current->next;
			}
			next=current->next;
			current->next= new node;
			current->next->elementNode=elementNode;
			current->next->next=next;
		}
		
	}
}

/*delete the first element*/
template <class T> void CSimpleLinkedList<T>::deleteToList(void)
{
	if(this->beginList==NULL)
	{
		return;
	}
	else
	{
		node* temp=this->beginList;
		this->beginList=this->beginList->next;
		delete temp;
	}
}

/*delete the entiere list*/
template <class T> void CSimpleLinkedList<T>::clearList(void)
{
	while (this->beginList!=NULL)
	{
		this->deleteToList();
	}
}

/*display the list with cout*/
template <class T> void CSimpleLinkedList<T>::displayList(void)
{
	if(this->beginList==NULL)
	{
		cout<<"List empty"<<endl;
	}
	else
	{
		node* temp=this->beginList;
		do
		{
			cout<<temp->elementNode<<endl<<endl;
			temp=temp->next;
		}
		while(temp!=NULL);
	}

}

/*return an element from the list. If the index is too big, it returns the last element.*/
template <class T> T CSimpleLinkedList<T>::getElement(int indexElement)
{
	/*node* temp=this->beginList;
	for(int i=0;i<indexElement;i++)
	{
		temp=temp->next;
	}
	return temp->elementNode;*/
	node* temp=this->beginList;
	int i=0;
	while(temp->next!=0 && i<indexElement)
	{
		temp=temp->next;
		i++;
	}
	return temp->elementNode;

}
#endif